package com.wanmait.recycle.util;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.wanmait.recycle.pojo.Userinfo;

public class EmailSendByMessage {

	
	private EmailSendByMessage() {}
	private static EmailSendByMessage emailSend = new EmailSendByMessage();
	public static EmailSendByMessage getEmailSend() {
		return emailSend;
	}
	
	
	public String sendEmail(String str,Userinfo userinfo) throws Exception {
		final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
		String email = userinfo.getMailBox(); 
		System.out.println(email);
		String[] str1 = email.split("@");
		String str2 = "smtp."+str1[1];
	    Properties prop = new Properties();
	    // 开启debug调试，以便在控制台查看
	    prop.setProperty("mail.debug", "false");
	    // 设置邮件服务器主机名
	    prop.setProperty("mail.host", str2);
	    // 发送服务器需要身份验证
	    prop.setProperty("mail.smtp.auth", "true");
	    // 发送邮件协议名称
	    prop.setProperty("mail.transport.protocol", "smtp");
	    prop.setProperty("mail.smtp.port", "465");
	    prop.setProperty("mail.smtp.socketFactory.port", "465");
	    prop.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);

	    //prop.put("mail.smtp.ssl.enable", "true");

	    // 创建session
	    Session session = Session.getInstance(prop);
	    // 通过session得到transport对象
	    Transport ts = null;
	   /* try {*/
	        ts = session.getTransport();
	   /* } catch (NoSuchProviderException e) {
	        e.printStackTrace();
	    }*/
	    // 连接邮件服务器：邮箱类型，帐号(12345678)换成发送人的QQ，授权码：hpifogzyvixdbfbh，这是我的，你要换成你自己的

	  /*  try {*/
	        ts.connect("smtp.mxhichina.com", "webmaster@qinglab.cn", "LzYl007993");// 后面的字符是授权码
	    /*} catch (MessagingException e) {
	        e.printStackTrace();
	    }*/
	    //随机生成四位数字
	   
	    MimeMessage message=null;

	     message=this.createSimpleMail(session,email,str);
	
	    System.out.println(message);

	        ts.sendMessage(message, message.getAllRecipients());
	        session.setDebug(true);

	        ts.close();
	
	   /* String cunt=stringBuilder.toString();*/
	    return null;
		
		
	}
	
	private MimeMessage createSimpleMail(Session session, String email, String str) throws Exception{
		// 创建邮件对象
	    MimeMessage message = new MimeMessage(session);
	    // 指明邮件的发件人...........@qq.com
	    message.setFrom(new InternetAddress("webmaster@qinglab.cn"));
	    // 指明邮件的收件人
	    message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
	    // 邮件的标题
	    message.setSubject("fenleiCX 通知：");
	    // 邮件的文本内容
	    message.setContent(str, "text/html;charset=UTF-8");
	    // 返回创建好的邮件对象
	    return message;

	}
	
}
